package com.pet.serve.service;

import com.pet.serve.entity.Customers;
import com.pet.serve.repository.CustomerRepository;
import com.pet.serve.security.CustomUserDetails;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import java.util.Optional;

@Service
public class CustomUserDetailsService implements UserDetailsService {

    private final CustomerRepository customerRepository; // Assume this is your repository

    public CustomUserDetailsService(CustomerRepository customerRepository) {
        this.customerRepository = customerRepository;
    }

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        System.out.println("Attempting to load user: " + username);
        Optional<Customers> customerOptional = customerRepository.findByUsername(username);

        if (customerOptional.isEmpty()) {
            System.out.println("User not found: " + username);
            throw new UsernameNotFoundException("User not found");
        }

        Customers customer = customerOptional.get();
        System.out.println("User found: " + customer.getUsername() + ", with permission: " + customer.getPermission());

        return new CustomUserDetails(customer, getAuthorities(customer));
    }

    private Collection<? extends GrantedAuthority> getAuthorities(Customers customer) {
        List<GrantedAuthority> authorities = new ArrayList<>();
        // 将 UserRole 枚举转换为字符串
        authorities.add(new SimpleGrantedAuthority(customer.getPermission().name()));
        return authorities;
    }
}
